-module(world_app).
-behaviour(application).
-include("common.hrl").
-export([start/2, stop/1]).

%% ====================================================================
%% API functions
%% ====================================================================


%% ====================================================================
%% Behavioural functions
%% ====================================================================

%% start/2
%% ====================================================================
%% @doc <a href="http://www.erlang.org/doc/apps/kernel/application.html#Module:start-2">application:start/2</a>
-spec start(Type :: normal | {takeover, Node} | {failover, Node}, Args :: term()) ->
	{ok, Pid :: pid()}
	| {ok, Pid :: pid(), State :: term()}
	| {error, Reason :: term()}.
%% ====================================================================
start(_Type, _StartArgs) ->
    Return = 'world_sup':start_link(),
	spawn(fun tk_config:preload_config/0),
	%%初始化 ID服务
	ets:new(?ETS_ID, [{keypos, 1}, set, public, named_table,?ETS_CONCURRENCY]),
	tk_id:init(),
    case data_setting:get(server_type) of
        normal ->
			ets:new(?ETS_ROLE_GATEWAY,[{keypos,#role_gateway.roleGWPID},named_table,set,public,?ETS_CONCURRENCY]),
	        ets:new(?ETS_ROLE_ONLINE,[{keypos,#role_online.roleID},named_table,set,public,?ETS_CONCURRENCY]),
	        start_(room_manager),
	        start_(room_sup),
	        start_(chat_server),
	        start_(role_public_server),
            ok;
        node_master ->
            start_(all_family_rank_server),
            start_(family_fight_master_server),  %% 联盟战主服务器
            start_(all_panic_buy_server),        %% 全区抢购
            start_(cross_talk_server);           %% 跨服喇叭
	    extremeFight_master ->
		    start_(extremeFight_master);
		Type ->
			?ERR("server type = ~w, world start nothing",[Type])
	end,
    Return.

%% stop/1
%% ====================================================================
%% @doc <a href="http://www.erlang.org/doc/apps/kernel/application.html#Module:stop-1">application:stop/1</a>
-spec stop(State :: term()) ->  Any :: term().
%% ====================================================================
stop(_State) ->
    ok.

%% ====================================================================
%% Internal functions
%% ====================================================================
start_(ServerName) ->
	try
		{ok, _} =
			supervisor:start_child(world_sup,
				{ServerName,
					{ServerName, start_link, []},
					permanent, 600000, worker, [ServerName]})
	catch
		_:Why ->
			?ERR("start_ ServerName=~p,Why=~p",[ServerName,Why])
	end.